from casevo.model_base import ModelBase
import networkx as nx
import pandas as pd
from typing import Dict, Any, List
import numpy as np

class OpinionModel(ModelBase):
    """观点演化模型类，用于模拟社交网络中的观点传播过程"""
    
    def __init__(self, config: Dict[str, Any]):
        """
        初始化观点演化模型
        
        Args:
            config: 配置参数字典
        """
        # 创建目标图（这里我们使用空图，因为我们会自己构建网络）
        tar_graph = nx.Graph()
        
        # 初始化LLM（这里我们使用None，因为我们不需要LLM功能）
        llm = None
        
        # 调用父类初始化
        super().__init__(tar_graph=tar_graph, llm=llm)
        
        self.config = config
        
        # 加载处理后的数据
        self.user_features = pd.read_csv('data/processed/user_features.csv')
        self.sentiment_data = pd.read_csv('data/processed/sentiment_analysis.csv')
        self.group_data = pd.read_csv('data/processed/group_clusters.csv')
        
        # 创建网络
        self.create_network()
        
        # 创建智能体
        self.create_agents()
        
        # 初始化数据收集器
        self.datacollector = None
        
    def create_network(self) -> None:
        """创建社交网络"""
        # 创建无标度网络
        self.graph = nx.barabasi_albert_graph(
            self.config['simulation']['num_agents'],
            self.config['network']['avg_degree'] // 2
        )
        
    def create_agents(self) -> None:
        """创建智能体"""
        from src.agents.opinion_agent import OpinionAgent
        
        # 为每个节点创建智能体
        for node in self.graph.nodes():
            agent = OpinionAgent(
                unique_id=node,
                model=self,
                description=f"观点智能体 {node}",
                context=self.config,
                user_features=self.user_features,
                sentiment_data=self.sentiment_data
            )
            self.add_agent(agent, node)
            
    def step(self) -> None:
        """执行模型的一个时间步"""
        # 更新所有智能体
        self.schedule.step()
        
        # 收集数据
        if self.datacollector:
            self.datacollector.collect(self)
            
    def get_network_metrics(self) -> Dict[str, float]:
        """
        获取网络指标
        
        Returns:
            Dict[str, float]: 包含网络指标的字典
        """
        return {
            'density': nx.density(self.graph),
            'clustering': nx.average_clustering(self.graph),
            'avg_degree': np.mean([d for n, d in self.graph.degree()]),
            'avg_path_length': nx.average_shortest_path_length(self.graph)
        }
        
    def get_opinion_stats(self) -> Dict[str, float]:
        """
        获取观点统计信息
        
        Returns:
            Dict[str, float]: 包含观点统计信息的字典
        """
        opinions = [agent.opinion for agent in self.schedule.agents]
        silent_ratio = sum(1 for agent in self.schedule.agents if agent.is_silent) / len(self.schedule.agents)
        
        # 按群体统计
        group_stats = {}
        for group_id in range(1, 4):
            group_agents = [agent for agent in self.schedule.agents if agent.group_id == group_id]
            if group_agents:
                group_opinions = [agent.opinion for agent in group_agents]
                group_stats[f'group_{group_id}_mean'] = np.mean(group_opinions)
                group_stats[f'group_{group_id}_silent'] = sum(1 for agent in group_agents if agent.is_silent) / len(group_agents)
        
        return {
            'mean_opinion': np.mean(opinions),
            'std_opinion': np.std(opinions),
            'silent_ratio': silent_ratio,
            **group_stats
        } 